import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import router from "@/router";

const request = axios.create({
  baseURL: "http://pcapi-xiaotuxian-front-devtest.itheima.net",
  timeout: 5000,
});

// axios请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.userInfo.token) {
      config.headers.Authorization = `Bearer ${userStore.userInfo.token}`;
    }
    return config;
  },
  (e) => Promise.reject(e)
);

// axios响应式拦截器
request.interceptors.response.use(
  (res) => res.data,
  async (e) => {
    const userStore = useUserStore();
    // 统一请求错误处理
    ElMessage({
      type: "warning",
      message: e.response.data.msg,
    });
    // 401token失效处理
    // 统一认证错误处理
    // 401处理优化
    if (e.response?.status === 401) {
      if (!isRefreshing) {
        isRefreshing = true;
        try {
          await refreshToken();
          return request(e.config); // 重试原请求
        } catch (refreshError) {
          userStore.clearUserStore();
          router.push({
            path: '/login',
            query: {
              redirect: router.currentRoute.value.fullPath,
              reason: 'SESSION_EXPIRED'
            }
          });
        } finally {
          isRefreshing = false;
        }
      }
      return Promise.reject(e);
    }
    // 处理网络错误
    if (!e.response) {
      ElMessage.error('网络连接异常，请检查网络后重试');
    }
    // 处理超时错误
    if (e.code === 'ECONNABORTED') {
      ElMessage.warning('请求超时，请稍后重试');
    }
    return Promise.reject(e);
  }
);

// token过期检查函数
let isRefreshing = false;
const refreshToken = async () => {
  try {
    const { data } = await axios.post('/refresh_token');
    useUserStore().setToken(data.token);
    return data.token;
  } catch (error) {
    throw new Error('刷新token失败');
  }
};

const isTokenExpired = (token) => {
  try {
    const { exp } = JSON.parse(atob(token.split('.')[1]));
    return Date.now() >= exp * 1000;
  } catch {
    return true;
  }
};

export default request;
